<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // 连接数据库
    $link = mysqli_connect("127.0.0.1", "root", "root", "database");

    // 获取参数
    $id = $_POST['id'];
    $name = $_POST['name'];

    // 查询当前节点的左值和父节点
    $query = "SELECT L, R, pid FROM tree_lr WHERE id = '{$id}'";
    $result = mysqli_query($link, $query);
    $row = mysqli_fetch_assoc($result);
    $l = $row['L'];
    $r = $row['R'];
    $pid = $row['pid'];

    // 查询左侧兄弟节点的左值和右值
    $query = "SELECT L, R FROM tree_lr WHERE R = '{$l}' - 1 AND pid = '{$pid}'";
    $result = mysqli_query($link, $query);
    $row = mysqli_fetch_assoc($result);
    $sl = $row['L'];
    $sr = $row['R'];

    // 新增节点的左值和右值
    $nl = $l;
    $nr = $l + 1;

    if (empty($sl)) {
        // 如果没有左侧兄弟节点，将新增节点作为第一个孩子节点
        $query = "UPDATE tree_lr SET L = L + 2, R = R + 2 WHERE R > '{$l}' AND pid = '{$pid}'";
        mysqli_query($link, $query);
    } else {
        // 如果有左侧兄弟节点，将新增节点插入左侧兄弟节点和当前节点之间
        $query = "UPDATE tree_lr SET R = R + 2 WHERE L > '{$sl}' AND pid = '{$pid}'";
        mysqli_query($link, $query);

        $nl = $sl + 1;
        $nr = $sl + 2;
    }

    // 插入数据，并设置左值和右值
    $query = "INSERT INTO tree_lr(name, pid, L, R, sex) VALUES ('{$name}', '{$pid}', '{$nl}', '{$nr}', '男')";
    $result = mysqli_query($link, $query);

    if ($result) {
        // 新增成功，返回成功信息
        echo json_encode(array('success' => true));
    } else {
        // 新增失败，返回错误信息
        echo json_encode(array('success' => false, 'message' => '新增失败，请稍后再试！'));
    }

    // 关闭连接
    mysqli_close($link);
}
